using UnityEngine;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using UnityEngine.Networking;
using System;

public class http
{
    public static async UniTask<string> Get(string url, IDictionary<string, string> paras = null, IDictionary<string, string> headers = null, IProgress<float> progress = null)
    {
        var request = UnityWebRequest.Get(url);
        if (headers != null)
        {
            foreach (var item in headers)
            {
                request.SetRequestHeader(item.Key, item.Value);
            }
        }
        if (url.StartsWith("https"))
        {
            request.certificateHandler = new BypassCertificate();
        }
        var result = await request.SendWebRequest().ToUniTask(progress);
        if (string.IsNullOrEmpty(result.error) == false)
        {
            Debug.LogError(url);
        }
        string content = result.downloadHandler.text;
        request.Dispose();
        return content;
    }


    public static async UniTask<byte[]> GetAsset(string url, IDictionary<string, string> paras = null, IDictionary<string, string> headers = null, IProgress<float> progress = null)
    {
        var request = UnityWebRequest.Get(url);
        if (headers != null)
        {
            foreach (var item in headers)
            {
                request.SetRequestHeader(item.Key, item.Value);
            }
        }
        if (url.StartsWith("https"))
        {
            request.certificateHandler = new BypassCertificate();
        }
        var result = await request.SendWebRequest().ToUniTask(progress);
        var resultContent = result.downloadHandler.data;
        request.Dispose();
        return resultContent;
    }

    public static UnityWebRequest requestAsset(string url, IDictionary<string, string> paras = null, IDictionary<string, string> headers = null)
    {
        var request = UnityWebRequest.Get(url);
        if (headers != null)
        {
            foreach (var item in headers)
            {
                Debug.Log(item.Key + "  " + item.Value);
                request.SetRequestHeader(item.Key, item.Value);
            }
        }
        if (url.StartsWith("https"))
        {
            request.certificateHandler = new BypassCertificate();
        }
        return request;
    }
}